package org.zsl.dao;

import java.sql.*;

public class DBUtil {


    private static Connection connection = null;

    private static PreparedStatement preparedStatement = null;

    private static ResultSet resultSet = null;


    private static String url = "jdbc:mysql://127.0.0.1:3306/demo";
    private static String username = "root";
    private static String password = "123456";


    public static Connection createConnection(){


        try {
            Class.forName("com.mysql.cj.jdbc.Driver"); // 注册驱动
            connection = DriverManager.getConnection(url, username, password);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return  connection;
    }

    public static ResultSet query(String sql,Object[] params){


        try {
            preparedStatement = connection.prepareStatement(sql);

            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i+1,params[i]);
            }

           resultSet=  preparedStatement.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return  resultSet;
    }


    public static  Boolean uptate(String sql,Object[] params){

        Boolean flag =false;

        try {
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i+1,params[i]);
            }

          flag=  preparedStatement.executeUpdate()>0;

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return  flag;
    }

}
